package org.codingq92.basic.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TestReentrantLock {
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private boolean flag = false;

    public void waitForFlag() throws InterruptedException {
        lock.lock();
        try {
            while (!flag) {
                System.out.println("等待condition条件队列中的线程被唤醒...");
                condition.await();
            }
            System.out.println("condition条件队列中的线程已经被唤醒，继续执行");
        } finally {
            lock.unlock();
        }
    }

    public void setFlag() {
        lock.lock();
        try {
            flag = true;
            System.out.println("唤醒所有的condition条件队列中的线程");
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        TestReentrantLock example = new TestReentrantLock();
        new Thread(() -> {
            try {
                example.waitForFlag();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(2000); // 模拟耗时操作
                example.setFlag();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
